import { PlusOutlined, UploadOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-components";
import {
  Avatar,
  Button,
  Card,
  Col,
  List,
  message,
  Row,
  Typography,
  Checkbox,
  Space,
  Spin,
} from "antd";
import { useEffect, useState, useRef } from "react";
import FaceDetail from "./components/FaceDetailForm";
import LocalUpload from "./components/LocalUploadForm";
import {
  createHighlights,
  getHistoryFolderFace,
  getHistoryFolderList,
} from "@/services/api/api-intelligent-processing";
import CompilationCreator from "./components/CompilationCreatorForm";

const IntelligentProcessing = () => {
  // 状态管理
  const [data, setData] = useState<ProcessingData.faces[]>([]);
  const [historyData, setHistoryData] = useState<ProcessingData.folderList[]>(
    []
  );
  const [selectedItem, setSelectedItem] = useState<number>();
  const [loading, setLoading] = useState(false);
  const [faceLoading, setFaceLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [historyPage, setHistoryPage] = useState(1);
  const [historyPageSize, setHistoryPageSize] = useState(10);
  const [historyTotal, setHistoryTotal] = useState(0);
  const [total, setTotal] = useState(0);
  const [hasMore, setHasMore] = useState(true);
  const containerRef = useRef<HTMLDivElement>(null);
  const [columns, setColumns] = useState(4);
  const [selectedFaces, setSelectedFaces] = useState<string[]>([]);
  const [showCompilationCreator, setShowCompilationCreator] = useState(false);
  const [isAllSelected, setIsAllSelected] = useState(false);
  const [creatingCompilation, setCreatingCompilation] = useState(false); // 新增：创建集锦加载状态

  // 处理人脸选择
  const handleFaceSelect = (faceId: string, checked: boolean) => {
    setSelectedFaces((prev) =>
      checked ? [...prev, faceId] : prev.filter((id) => id !== faceId)
    );
  };

  // 清除所有选中状态
  const clearAllSelections = () => {
    setSelectedFaces([]);
    setIsAllSelected(false);
  };

  // 全选/取消全选
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      // 选择所有当前已加载的人脸
      const allFaceIds = data.map((item) => item.face_group_id || item.id);
      setSelectedFaces(allFaceIds);
      setIsAllSelected(true);
    } else {
      clearAllSelections();
    }
  };

  // 直接创建集锦
  const handleCreateCompilationDirectly = async () => {
    if (selectedFaces.length === 0) {
      message.warning("请先选择要创建集锦的人脸");
      return;
    }

    setCreatingCompilation(true); // 开始创建，显示加载状态

    try {
      const res = await createHighlights({
        folder_id: selectedItem,
        face_group_ids: selectedFaces,
      });

      message.success(`成功创建包含 ${selectedFaces.length} 个人脸的集锦`);
      clearAllSelections();
    } catch (error) {
      message.error("创建集锦失败");
    } finally {
      setCreatingCompilation(false); // 无论成功失败，都结束加载状态
    }
  };

  // 常量定义
  const CONTAINER_HEIGHT = 700;
  const CARD_WIDTH = 130;
  const CARD_GAP = 16;

  // 计算当前可显示的列数
  const calculateColumns = () => {
    if (!containerRef.current) return 4;
    const containerWidth = containerRef.current.clientWidth;
    return Math.max(1, Math.floor(containerWidth / (CARD_WIDTH + CARD_GAP)));
  };

  // 加载数据函数
  const loadMoreData = async () => {
    if (loading || !hasMore || !selectedItem) return;
    setLoading(true);

    try {
      const currentColumns = calculateColumns();
      const loadCount = currentColumns * 4;

      const res = await getHistoryFolderFace({
        id: selectedItem,
        currentPage: page,
        pageSize: loadCount,
      });

      const newData = res.data.data;
      const totalCount = res.data.total;

      setTotal(totalCount);
      setHasMore(data.length + newData.length < totalCount);

      setData((prev) => [...prev, ...newData]);
      setPage((prev) => prev + 1);

      if (newData.length > 0) {
        message.success(`加载了${newData.length}条数据`);
      } else {
        message.info("没有更多数据了");
      }
    } catch (err) {
      message.error("数据加载失败");
    } finally {
      setLoading(false);
    }
  };

  // 加载历史数据
  const loadHistoryData = async (page: number = 1, pageSize: number = 10) => {
    setFaceLoading(true);
    try {
      const res = await getHistoryFolderList({
        currentPage: page,
        pageSize: pageSize,
      });
      setHistoryData(res.data.data);
      setHistoryTotal(res.data.total);
      setHistoryPage(page);
      setHistoryPageSize(pageSize);

      // 默认选中第一项
      if (res.data.data.length > 0 && !selectedItem) {
        fetchItemDetail(res.data.data[0].id);
      }
    } catch (err) {
      message.error("历史数据加载失败");
    } finally {
      setFaceLoading(false);
    }
  };

  // 根据ID获取详情
  const fetchItemDetail = async (id: number) => {
    try {
      // 重置分页状态
      setPage(1);
      setData([]);
      setHasMore(true);
      setSelectedItem(id);
      clearAllSelections(); // 清空已选中的face

      const res = await getHistoryFolderFace({
        id,
        currentPage: 1,
        pageSize: calculateColumns() * 4,
      });
      const item = res.data.data;
      setTotal(res.data.total);
      setHasMore(item.length < res.data.total);
      setData(item);
    } catch (err) {
      message.error("获取详情失败");
    }
  };

  // 历史记录分页变化处理
  const handleHistoryPageChange = (page: number, pageSize?: number) => {
    loadHistoryData(page, pageSize || historyPageSize);
  };

  // 初始加载
  useEffect(() => {
    const handleResize = () => {
      setColumns(calculateColumns());
    };

    handleResize();
    loadHistoryData();

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  // 更新全选状态
  useEffect(() => {
    if (data.length > 0) {
      const allLoadedFaceIds = data.map(
        (item) => item.face_group_id || item.id
      );
      const allSelected =
        allLoadedFaceIds.length > 0 &&
        allLoadedFaceIds.every((id) => selectedFaces.includes(id));
      setIsAllSelected(allSelected);
    } else {
      setIsAllSelected(false);
    }
  }, [selectedFaces, data]);

  // 滚动事件处理
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const handleScroll = () => {
      const { scrollTop, scrollHeight, clientHeight } = container;
      if (
        scrollHeight - scrollTop <= clientHeight + 50 &&
        !loading &&
        hasMore
      ) {
        loadMoreData();
      }
    };

    container.addEventListener("scroll", handleScroll);
    return () => container.removeEventListener("scroll", handleScroll);
  }, [loading, columns, hasMore, selectedItem]);

  return (
    <PageContainer
      header={{
        title: "智能处理",
        breadcrumb: {},
      }}
      extra={[
        <LocalUpload onClose={() => {}} />,
        <Space>
          <Button
            key="create-compilation"
            type="primary"
            icon={<PlusOutlined />}
            disabled={selectedFaces.length === 0 || creatingCompilation} // 创建中禁用按钮
            onClick={handleCreateCompilationDirectly}
          >
            {creatingCompilation ? (
              <Spin size="small" style={{ marginRight: 8 }} />
            ) : null}
            创建集锦 ({selectedFaces.length})
          </Button>
        </Space>,
      ]}
    >
      <Row gutter={16}>
        <Col span={8}>
          <Card title="历史记录" loading={faceLoading}>
            <List
              bordered
              dataSource={historyData}
              renderItem={(item) => (
                <List.Item
                  onClick={() => fetchItemDetail(item.id)}
                  style={{
                    cursor: "pointer",
                    backgroundColor:
                      selectedItem === item.id ? "#e6f7ff" : "inherit",
                  }}
                >
                  <List.Item.Meta title={<a>{item.path}</a>} />
                </List.Item>
              )}
              pagination={{
                current: historyPage,
                pageSize: historyPageSize,
                total: historyTotal,
                onChange: handleHistoryPageChange,
                onShowSizeChange: handleHistoryPageChange,
                showSizeChanger: true,
                showTotal: (total) => `共 ${total} 条记录`,
                pageSizeOptions: ["10", "20", "50", "100"],
              }}
            />
          </Card>
        </Col>
        <Col span={16}>
          <Card
            title={
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <div>
                  <span>监测到的人脸</span>
                  {selectedFaces.length > 0 && (
                    <Typography.Text type="secondary">
                      (已选择 {selectedFaces.length} 项)
                    </Typography.Text>
                  )}
                </div>
                <Checkbox
                  checked={isAllSelected}
                  indeterminate={selectedFaces.length > 0 && !isAllSelected}
                  onChange={(e) => handleSelectAll(e.target.checked)}
                  disabled={creatingCompilation} // 创建中禁用全选
                >
                  全选
                </Checkbox>
              </div>
            }
          >
            <div
              ref={containerRef}
              style={{
                height: CONTAINER_HEIGHT,
                overflow: "auto",
                padding: "8px",
                border: "1px solid #f0f0f0",
                borderRadius: "8px",
              }}
            >
              {/* 创建集锦时的全局遮罩层 */}
              {creatingCompilation && (
                <div
                  style={{
                    position: "absolute",
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    backgroundColor: "rgba(255, 255, 255, 0.7)",
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    zIndex: 1000,
                    borderRadius: "8px",
                  }}
                >
                  <Spin size="large" tip="集锦创建中，请稍候..." />
                </div>
              )}

              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: `repeat(auto-fill, ${CARD_WIDTH}px)`,
                  justifyContent: "space-between",
                  gap: `${CARD_GAP}px`,
                  paddingBottom: "40px",
                  position: "relative", // 为遮罩层定位提供参考
                }}
              >
                {data.map((item) => (
                  <FaceDetail
                    folderId={selectedItem}
                    key={item.id}
                    record={item}
                    onRefurbish={() => {}}
                    selected={selectedFaces.includes(
                      item.face_group_id || item.id
                    )}
                    onSelectChange={(checked) =>
                      handleFaceSelect(item.face_group_id || item.id, checked)
                    }
                    disabled={creatingCompilation} // 传递给子组件，禁用选择
                  />
                ))}
              </div>
              {loading && (
                <div
                  style={{
                    padding: "16px",
                    textAlign: "center",
                    position: "sticky",
                    bottom: 0,
                    background:
                      "linear-gradient(transparent, rgba(255,255,255,0.9))",
                  }}
                >
                  <div
                    style={{
                      display: "inline-flex",
                      alignItems: "center",
                      gap: 8,
                      padding: "8px 16px",
                      background: "#fff",
                      borderRadius: 20,
                      boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
                    }}
                  >
                    <div
                      style={{
                        width: 12,
                        height: 12,
                        borderRadius: "50%",
                        border: "2px solid #1890ff",
                        borderTopColor: "transparent",
                        animation: "spin 1s linear infinite",
                      }}
                    />
                    <span style={{ color: "#1890ff" }}>加载更多...</span>
                  </div>
                </div>
              )}
              {!hasMore && data.length > 0 && (
                <div
                  style={{
                    textAlign: "center",
                    padding: "16px",
                    color: "#999",
                  }}
                >
                  没有更多数据了
                </div>
              )}
            </div>
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};

export default IntelligentProcessing;
